package com.mybatis.generator.utils;

import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

public class FileUtil {

    /**
     * 根据目录生产文件
     * @param variables 模板变量名
     * @param savePath 文件保存路径
     * @param fileName 文件名
     * @param template 模板类
     * @param isOverwrite 是否覆盖
     */
    public static void buildTemplate(Map<String, Object> variables, String savePath, String fileName, Template template, boolean isOverwrite) {
        File newsDir = new File(savePath);
        if (!newsDir.exists()) {
            newsDir.mkdirs();
        }
        String realFileName = savePath + fileName;
        boolean isCreate = true;
        try {
            File realFile = new File(realFileName);
            if (realFile.exists()) {
                if (!isOverwrite) {
                    isCreate = false;
                }
            }
            if (isCreate) {
                Writer out = new OutputStreamWriter(new FileOutputStream(realFileName), "UTF-8");
                template.process(variables, out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String genFilePathByPackage(String packageParam) {
        if(StringUtils.isBlank(packageParam)) {
            return "";
        }

        packageParam = packageParam.replaceAll(" ", "");
        return packageParam.replaceAll("\\.", "/");
    }

}
